package com.bcbim.operation_maintenance.space.service;

import com.bcbim.common.util.ExcelUtil;
import com.bcbim.operation_maintenance.space.mapper.SpaceMapper;
import com.bcbim.operation_maintenance.table_head.mapper.SpaceDepartmentTableHeadMapper;
import com.bcbim.operation_maintenance.table_head.mapper.SpaceTableHeadMapper;
import com.bcbim.operation_maintenance.table_head.mapper.SpaceTypeTableHeadMapper;
import com.bcbim.operation_maintenance_interface.business_department.vo.ListBusinessDepartmentTreeVO;
import com.bcbim.operation_maintenance_interface.space.dao.SpaceDAO;
import com.bcbim.operation_maintenance_interface.space.dao.SpaceRecordDAO;
import com.bcbim.operation_maintenance_interface.space.dto.SpaceColorTypeDTO;
import com.bcbim.operation_maintenance_interface.space.dto.SpaceDTO;
import com.bcbim.operation_maintenance_interface.space.dto.SpaceInfoDTO;
import com.bcbim.operation_maintenance_interface.space.dto.SpaceUnassignedDTO;
import com.bcbim.operation_maintenance_interface.space.service.SpaceService;
import com.bcbim.operation_maintenance_interface.space.vo.*;
import com.bcbim.operation_maintenance_interface.space_category.vo.ListSpaceCategoryTreeVO;
import com.bcbim.operation_maintenance_interface.space_type.vo.ListSpaceTypeVO;
import com.bcbim.operation_maintenance_interface.table_head.vo.SpaceDepartmentTableHeadVO;
import com.bcbim.operation_maintenance_interface.table_head.vo.SpaceTableHeadVO;
import com.bcbim.operation_maintenance_interface.table_head.vo.SpaceTypeTableHeadVO;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.Service;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * @version V 1.0.0
 * @Description：空间信息表(t_space)表实现类
 * @Author: haomeijie
 * @Date: 2022/3/8 13:29
 **/
@Service(timeout = 60 * 1000, group = "space", version = "1.0.0")
public class SpaceServiceImpl implements SpaceService {

    @Autowired
    private SpaceMapper spaceMapper;
    @Autowired
    private SpaceTableHeadMapper spaceTableHeadMapper;
    @Autowired
    private SpaceTypeTableHeadMapper spaceTypeTableHeadMapper;
    @Autowired
    private SpaceDepartmentTableHeadMapper spaceDepartmentTableHeadMapper;


    @Override
    public List<ListSpaceVO> listSpace(SpaceDTO spaceDTO) {
        return spaceMapper.listSpace(spaceDTO);
    }

    @Override
    public List<ListSpaceInfoVO> listSpaceInfo(SpaceInfoDTO spaceInfoDTO) {
        return spaceMapper.listSpaceInfo(spaceInfoDTO);
    }

    @Override
    public int listSpaceInfoCount(SpaceInfoDTO spaceInfoDTO) {
        return spaceMapper.listSpaceInfoCount(spaceInfoDTO);
    }

    @Override
    public SpaceVO getSpace(String id) {
        return spaceMapper.getSpace(id);
    }

    @Override
    public int updateSpace(SpaceDAO spaceDAO) {
        return spaceMapper.updateSpace(spaceDAO);
    }

    @Override
    public List<ListSpaceAssignVO> getSpaceByMaterial(String[] serverIds) {
        return spaceMapper.getSpaceByMaterial(serverIds);
    }

    @Override
    public void updateSpaceType(SpaceUnassignedDTO spaceUnassignedDTO) {
        spaceMapper.updateSpaceType(spaceUnassignedDTO);
    }

    @Override
    public void updateDepartment(SpaceUnassignedDTO spaceUnassignedDTO) {
        spaceMapper.updateDepartment(spaceUnassignedDTO);
    }

    @Override
    public String exportSpace(SpaceInfoDTO spaceInfoDTO, String userId, String path) {
        //获取用户勾选的信息表头
        List<SpaceTableHeadVO> spaceTableHead = spaceTableHeadMapper.selectCheckedTableByUserId(userId, spaceInfoDTO.getProjectId());
        //整理表头内容，生成导出模板
        String filename = "space.xls";
        String[] title = new String[spaceTableHead.size()];
        String[][] content = new String[1][title.length];
        for (int i = 0; i < spaceTableHead.size(); i++) {
            title[i] = spaceTableHead.get(i).getLabel();
            content[0][i] = String.valueOf("${list." + spaceTableHead.get(i).getProp() + "}");
        }
        //创建模板文件
        checkedFolder(path + "template");
        File templateFile = new File(path + "template" + File.separator + filename);
        //生成导出模板
        GenerateTemplate(title, content, templateFile);
        //创建导出文件
        checkedFolder(path + "export");
        String filepath = "export" + File.separator + "空间信息.xls";
        File file = new File(path + filepath);
        //查询列表数据
        List<ListSpaceInfoVO> list = spaceMapper.listSpaceInfo(spaceInfoDTO);
        Map<String, Object> param = new HashMap<>();
        param.put("list", list);
        try {
            //进行数据导出
            ExcelUtil.downLoadExcel(templateFile, file, param);
            return filepath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String exportCategory(List<ListSpaceCategoryTreeVO> list, String userId, String projectId, String path) {
        //获取用户勾选的信息表头
        List<SpaceTypeTableHeadVO> spaceTableHead = spaceTypeTableHeadMapper.selectCheckedTableByUserId(userId, projectId);
        //整理表头内容，生成导出模板
        String filename = "spaceCategory.xls";
        String[] title = new String[spaceTableHead.size()];
        String[][] content = new String[1][title.length];
        for (int i = 0; i < spaceTableHead.size(); i++) {
            title[i] = spaceTableHead.get(i).getLabel();
            content[0][i] = String.valueOf("${list." + spaceTableHead.get(i).getProp() + "}");
        }
        //创建模板文件
        checkedFolder(path + "template");
        File templateFile = new File(path + "template" + File.separator + filename);
        //生成导出模板
        GenerateTemplate(title, content, templateFile);
        //创建导出文件
        checkedFolder(path + "export");
        String filepath = "export" + File.separator + "类别类型.xls";
        File file = new File(path + filepath);
        //查询列表数据
        List<ListSpaceTypeVO> spaceTypeList = new ArrayList<>();
        for (ListSpaceCategoryTreeVO treeVO : list) {
            ListSpaceTypeVO listSpaceTypeVO = new ListSpaceTypeVO();
            listSpaceTypeVO.setSpaceCategory(treeVO.getSpaceCategory());
            listSpaceTypeVO.setColor(treeVO.getColor());
            listSpaceTypeVO.setSpaceCount(treeVO.getSpaceCount());
            listSpaceTypeVO.setSpaceArea(treeVO.getSpaceArea());
            spaceTypeList.add(listSpaceTypeVO);
            if (ObjectUtils.isNotEmpty(treeVO.getChildList())) {
                treeVO.getChildList().stream().forEach(tree -> {
                    ListSpaceTypeVO spaceTypeVO = new ListSpaceTypeVO();
                    spaceTypeVO.setSpaceType(tree.getSpaceType());
                    spaceTypeVO.setColor(tree.getColor());
                    spaceTypeVO.setSpaceCount(tree.getSpaceCount());
                    spaceTypeVO.setSpaceArea(tree.getSpaceArea());
                    spaceTypeList.add(spaceTypeVO);
                });
            }
        }
        Map<String, Object> param = new HashMap<>();
        param.put("list", spaceTypeList);
        try {
            //进行数据导出
            ExcelUtil.downLoadExcel(templateFile, file, param);
            return filepath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String exportDepartment(List<ListBusinessDepartmentTreeVO> list, String userId, String projectId, String path) {
        //获取用户勾选的信息表头
        List<SpaceDepartmentTableHeadVO> spaceTableHead = spaceDepartmentTableHeadMapper.selectCheckedTableByUserId(userId, projectId);
        //整理表头内容，生成导出模板
        String filename = "spaceDepartment.xls";
        String[] title = new String[spaceTableHead.size()];
        String[][] content = new String[1][title.length];
        for (int i = 0; i < spaceTableHead.size(); i++) {
            title[i] = spaceTableHead.get(i).getLabel();
            content[0][i] = String.valueOf("${list." + spaceTableHead.get(i).getProp() + "}");
        }
        //创建模板文件
        checkedFolder(path + "template");
        File templateFile = new File(path + "template" + File.separator + filename);
        //生成导出模板
        GenerateTemplate(title, content, templateFile);
        //创建导出文件
        checkedFolder(path + "export");
        String filepath = "export" + File.separator + "业务部部门.xls";
        File file = new File(path + filepath);
        //查询列表数据
        List<ListBusinessDepartmentTreeVO> spaceTypeList = new ArrayList<>();
        for (ListBusinessDepartmentTreeVO treeVO : list) {
            ListBusinessDepartmentTreeVO businessDepartment = new ListBusinessDepartmentTreeVO();
            businessDepartment.setBusinessDepartmentName(treeVO.getBusinessDepartmentName());
            businessDepartment.setColor(treeVO.getColor());
            businessDepartment.setSpaceCount(treeVO.getSpaceCount());
            businessDepartment.setSpaceArea(treeVO.getSpaceArea());
            spaceTypeList.add(businessDepartment);
            if (ObjectUtils.isNotEmpty(treeVO.getChildList())) {
                treeVO.getChildList().stream().forEach(tree -> {
                    ListBusinessDepartmentTreeVO department = new ListBusinessDepartmentTreeVO();
                    department.setDepartmentName(tree.getDepartmentName());
                    department.setColor(tree.getColor());
                    department.setSpaceCount(tree.getSpaceCount());
                    department.setSpaceArea(tree.getSpaceArea());
                    spaceTypeList.add(department);
                });
            }
        }
        Map<String, Object> param = new HashMap<>();
        param.put("list", spaceTypeList);
        try {
            //进行数据导出
            ExcelUtil.downLoadExcel(templateFile, file, param);
            return filepath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Double getSpaceAreaSum(String[] serverIds) {
        return spaceMapper.getSpaceAreaSum(serverIds);
    }

    @Override
    public List<SpaceColorVO> selectSpaceByColor(SpaceColorTypeDTO spaceColorTypeDTO) {
        return spaceMapper.selectSpaceByColor(spaceColorTypeDTO);
    }

    @Override
    public List<SpaceLabelVO> selectSpaceByLabel(SpaceColorTypeDTO spaceColorTypeDTO) {
        return spaceMapper.selectSpaceByLabel(spaceColorTypeDTO);
    }

    @Override
    public int batchInsert(List<SpaceDAO> list) {
        return spaceMapper.batchInsert(list);
    }

    /**
     * 生成时间戳
     *
     * @Author: haomeijie
     * @Date: 2022/3/18 14:03
     */
    public String getTimeStamp() {
        SimpleDateFormat sdf = null;
        sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStamp = sdf.format(new Date());
        return timeStamp;
    }

    //判断文件夹是否存在
    public void checkedFolder(String fold) {
        File folder = new File(fold);
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    /**
     * 在本地生成导出文件模板
     *
     * @Author: haomeijie
     * @Date: 2022/3/18 14:03
     */
    public void GenerateTemplate(String[] title, String[][] content, File file) {
        String sheetName = "Sheet1";

        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        try {
            FileOutputStream output = new FileOutputStream(file);
            wb.write(output);//写入磁盘
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取变更次数
     *
     * @param spaceId
     * @author xuehao
     * @createDate 2022/4/28 10:20
     * @retuen int
     */
    @Override
    public int getUpdateCount(String spaceId) {
        return spaceMapper.getUpdateCount(spaceId);
    }

    /**
     * 新增变更记录
     *
     * @param spaceRecordDAO
     * @author xuehao
     * @createDate 2022/4/28 10:32
     * @retuen int
     */
    @Override
    public int insertSpaceRecord(SpaceRecordDAO spaceRecordDAO) {
        return spaceMapper.insertSpaceRecord(spaceRecordDAO);
    }

    /**
     * 编辑变更记录
     *
     * @param spaceRecordDAO
     * @author xuehao
     * @createDate 2022/4/28 10:36
     * @retuen int
     */
    @Override
    public int updateSpaceRecord(SpaceRecordDAO spaceRecordDAO) {
        return spaceMapper.updateSpaceRecord(spaceRecordDAO);
    }

    /**
     * 保存变更记录
     *
     * @param spaceRecordDAO
     * @author xuehao
     * @createDate 2022/4/28 10:44
     * @retuen void
     */
    @Override
    public void saveSpaceRecord(SpaceRecordDAO spaceRecordDAO) {
        //如果没有记录则新增,有则覆盖
        spaceRecordDAO.setChangeDate(LocalDate.now());
        int updateCount = spaceMapper.getUpdateCount(spaceRecordDAO.getSpaceId());
        if (updateCount > 0) {
            spaceMapper.updateSpaceRecord(spaceRecordDAO);
        } else {
            spaceMapper.insertSpaceRecord(spaceRecordDAO);
        }
    }

    /**
     * 查询空间变更列表
     *
     * @param spaceId
     * @author xuehao
     * @createDate 2022/4/28 13:44
     * @retuen List<SpaceRecordListVO>
     */
    @Override
    public List<SpaceRecordListVO> listSpaceRecord(String spaceId) {
        return spaceMapper.listSpaceRecord(spaceId);
    }

    @Override
    public int deleteSpaceByBuildId(String buildId) {
        return spaceMapper.deleteSpaceByBuildId(buildId);
    }

    @Override
    public int deleteSpaceByModelFileId(String modelFileId) {
        return spaceMapper.deleteSpaceByModelFileId(modelFileId);
    }

    @Override
    public boolean checkSpaceExitStaff(String[] spaceIds) {
        return spaceMapper.checkSpaceExitStaff(spaceIds) > 0 ? true : false;
    }
}
